import axios from "axios";
import { getOssPolicy } from "@/api/paper";

class MyUploadAdapter {
  constructor(loader, index) {
    this.loader = loader;
    this.index = index;
  }
  getRandom(min, max) {
    return Math.round(Math.random() * (max - min) + min);
  }
  getCode() {
    var _this = this;
    let code = "";
    for (var i = 0; i < 6; i++) {
      var type = _this.getRandom(1, 3);
      switch (type) {
        case 1:
          code += String.fromCharCode(_this.getRandom(48, 57)); //数字
          break;
        case 2:
          code += String.fromCharCode(_this.getRandom(65, 90)); //大写字母
          break;
        case 3:
          code += String.fromCharCode(_this.getRandom(97, 122)); //小写字母
          break;
      }
    }
    return code;
  }
  async upload() {
    var _this = this;
    var file = await this.loader.file;
    var idx = this.index;
    let json;
    await getOssPolicy({}).then((res) => {
      json = res;
    });
    var AuthMsg = json;
    var arrIndex = file.name.split(".").length - 1;
    var imgExit = file.name.split(".")[arrIndex];
    var rand = _this.getCode();
    var ossKey = AuthMsg.dir + rand + "_" + idx + "." + imgExit;
    var imgurl = AuthMsg.host + "/" + ossKey;
    // // 添加签名信息
    var ossData = new FormData();
    ossData.append("OSSAccessKeyId", AuthMsg.accessid);
    ossData.append("policy", AuthMsg.policy);
    ossData.append("Signature", AuthMsg.signature);
    ossData.append("key", ossKey);
    // // 添加文件
    ossData.append("file", file, rand);
    ossData.append("success_action_status", 200);
    let config = {
      headers: {
        "Content-Type": "application/octet-stream",
      },
    }; //添加请求头
    const res = await axios
      .post(AuthMsg.host, ossData, config)
      .then((res) => {
        console.log(res);
        return imgurl;
      })
      .catch(function(error) {
        console.log(error);
      });
    return {
      default: res,
    };
  }
}

export default MyUploadAdapter;
